package pl.edu.agh.soa.monitoring.endpoints.impl;

import java.util.List;
import java.util.Map;

import javax.jbi.management.DeploymentException;
import javax.jbi.messaging.ExchangeStatus;
import javax.jbi.messaging.MessageExchange;
import javax.jbi.messaging.NormalizedMessage;

import org.apache.log4j.Logger;
import org.apache.servicemix.common.endpoints.ProviderEndpoint;

import pl.edu.agh.soa.monitoring.cep.CEPProvider;
import pl.edu.agh.soa.monitoring.cep.event.TestEvent;
import pl.edu.agh.soa.monitoring.endpoints.IReceiverEndpoint;
import pl.edu.agh.soa.monitoring.router.entry.DynamicRouterEntry;

/**
 * @org.apache.xbean.XBean element="receiverEndpoint"
 */
public class ReceiverEndpoint extends ProviderEndpoint implements
		IReceiverEndpoint {

	private final static Logger logger = Logger
			.getLogger(ReceiverEndpoint.class);

	private CEPProvider.ICEPProvider cepProvider;

	public void validate() throws DeploymentException {
	}

	@Override
	public void activate() {
		try {
			super.activate();
			initComponent();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void initComponent() {
		// register ESP/CEP engine
		cepProvider = CEPProvider.getCEPProvider();
		cepProvider.init();
	}

	protected void processInOnly(MessageExchange exchange, NormalizedMessage in)
			throws Exception {
		if (exchange.getStatus() == ExchangeStatus.DONE) {
			return;
			// Exchange has been aborted with an exception
		} else if (exchange.getStatus() == ExchangeStatus.ERROR) {
			return;
			// Exchange is active
		} else if (exchange.getStatus() == ExchangeStatus.ACTIVE) {
			new ReceiverThread(in,exchange).start();
		}
	}

	class ReceiverThread extends Thread {

		NormalizedMessage in;
		MessageExchange exchange;
		
		public ReceiverThread(NormalizedMessage in, MessageExchange exchange) {
			this.in = in;
			this.exchange = exchange;
		}

		public void run() {
			Object nameObj = exchange.getProperty("name");
			Object valueObj = exchange.getProperty("value");
			if (nameObj != null && valueObj != null){
				TestEvent temp = new TestEvent((String)nameObj, Integer.valueOf((String)valueObj));
				cepProvider.sendEvent(temp);
			}
		}
	}

	public void register(String statementID,
			Map<String, List<String>> callbackAddresses) {
		DynamicRouterEntry entry = new DynamicRouterEntry();
		entry.setCallbackAddresses(callbackAddresses);
		entry.setStatementID(statementID);
		cepProvider.registerStatement(statementID, entry);	
	}

	public Map<String, List<DynamicRouterEntry>> getRoutingMap() {
		return cepProvider.getDynamicRouter().getRoutingMap();
	}
}
